import json

import requests
from utils.log_utils import logger


class BaseApi:

    def __init__(self, base_url):
        self.base_url = base_url

    def __set_token(self, request_infos):
        """token获取与设置"""
        admin_url = 'admin/auth/login'
        admin_data = {"username": "hogwarts", "password": "test12345", "code": ""}
        admin_r = requests.request("post", self.base_url + admin_url, json=admin_data)
        self.token = {"X-Litemall-Admin-Token": admin_r.json()['data']['token']}

        # 获取headers，如果请求本身有头信息，那么就把token信息更新进去
        if request_infos.get("headers"):
            # 防止覆盖其他的头信息
            request_infos["headers"].update(self.token)
        else:
            request_infos["headers"] = self.token
        return request_infos

    def send_req(self, method, url, **kwargs):
        kwargs = self.__set_token(kwargs)
        r = requests.request(method, self.base_url + url, **kwargs)
        logger.debug(f"{url}接口的响应值为{json.dumps(r.json(), indent=2, ensure_ascii=False)}")
        return r
